<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div>
    <h1>数据劫持</h1>
  </div>
</body>
<script>


  function defineReactive(obj, key, value) {

    observe(value)

    Object.defineProperty(obj, key, {
      get() {
        return value
      },
      set(newVal) {
        console.log(newVal, "newValue");
        value = newVal
      }
    })

  }



  function observe(obj) {
    console.log(obj, "observe传的数据");

    //因为是递归调用,所以需要判断,如果obj不是对象,则直接return,不需要深层次响应式处理
    if (typeof obj !== "object" || obj === null) return;

    for (let key of Object.keys(obj)) {

      defineReactive(obj, key, obj[key])

    }


  }


  let vm = {
    _data: {
      name: "xiaoming",
      age: 22,
      count: 0,
      movies: {
        name: "迷雾",
        price: 199
      }
    }
  }

  //调用观察者函数  把要监听的数据传过去
  observe(vm._data)



</script>

</html>